package tss.datastore.meta;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public class EntityDefinition implements Externalizable {

    private long entityId;    
    private Map<String, AttributeDefinition> attributes;

    public EntityDefinition(long entityId) {
        this.entityId = entityId;
        this.attributes = new HashMap<>();
    }
    
    public EntityDefinition() {
        
    }

    public long getId() {
        return entityId;
    }

    public boolean AddAttribute(AttributeDefinition attributeDefinition) {
        String attributeName = attributeDefinition.getName();
        if (attributes.containsKey(attributeName)) {
            return false;
        } else {
            attributes.put(attributeName, attributeDefinition);
            return true;
        }        
    }
    
    public Collection<AttributeDefinition> getAttributes() {
        return attributes.values();
    }

    @SuppressWarnings("unchecked")
    @Override
    public void readExternal(ObjectInput input) throws IOException, ClassNotFoundException {
        this.entityId = input.readLong();
        Collection<AttributeDefinition> list = (Collection<AttributeDefinition>) input.readObject();
        this.attributes = new HashMap<>();
        for (AttributeDefinition each : list) {
            this.attributes.put(each.getName(), each);
        }
    }

    @Override
    public void writeExternal(ObjectOutput output) throws IOException {
        output.writeLong(this.entityId);
        output.writeObject(new ArrayList<AttributeDefinition>(attributes.values()));        
    }
    
    @Override
    public boolean equals(Object obj) {
        if (obj instanceof EntityDefinition) {
            EntityDefinition other = (EntityDefinition) obj;
            return this.entityId == other.entityId;
        } else {
            return false;
        }
    }

    @Override
    public int hashCode() {
        return (int) entityId * 17;
    }

    public AttributeDefinition getAttribute(String attributeName) {        
        return attributes.get(attributeName);
    }
    
}
